package com.instreet.idra.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.instreet.idra.model.Game;
import com.instreet.idra.service.IGameService;

@Controller
public class GameController {
	
	public IGameService gameService;
	public IGameService getGameService() {
		return gameService;
	}
	public void setGameService(IGameService gameService) {
		this.gameService = gameService;
	}
	
	@RequestMapping(value="/home")
	public ModelAndView listGame(ModelAndView model) throws IOException{
		List<Game> listGame = gameService.list();
		model.addObject("listGame", listGame);
		model.setViewName("home");
		return model;
	}
	
	@RequestMapping(value = "/newGame", method = RequestMethod.GET)
	public ModelAndView newGame(ModelAndView model) {
		Game game = new Game();
	    model.addObject("game", game);
	    model.setViewName("gameForm");
	    return model;
	}
	
	@RequestMapping(value = "/saveGame", method = RequestMethod.POST)
	public ModelAndView saveGame(@ModelAttribute Game game) {
		gameService.saveOrUpdate(game);
	    return new ModelAndView("redirect:/home");
	}
	
	@RequestMapping(value = "/deleteGame", method = RequestMethod.GET)
	public ModelAndView deleteGame(HttpServletRequest request) {
	    Long id = Long.valueOf(request.getParameter("id"));
	    gameService.delete(id);
	    return new ModelAndView("redirect:/home");
	}
	
	@RequestMapping(value = "/editGame", method = RequestMethod.GET)
	public ModelAndView editContact(HttpServletRequest request) {
		Long id = Long.valueOf(request.getParameter("id"));
		Game game = gameService.select(id);
	    ModelAndView model = new ModelAndView("gameForm");
	    model.addObject("game", game);
	    return model;
	}
}
